package com.dzm.factory;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 作者：Dzm
 * 时间：2024-08-23-10:03
 * 功能：
 */

@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        Predicate<ServerWebExchange> exchangePredicate = new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
                if (StrUtil.isNotBlank(ageStr)) {
                    int age = Integer.parseInt(ageStr);
                    return age <= config.getMaxAge() && age >= config.getMinAge();
                }
                return false;
            }
        };
        return exchangePredicate;
    }

    @Data
    public static class Config{
        private Integer minAge;
        private Integer maxAge;
    }
}
